﻿#include "videoplayer.h"

VideoPlayer::VideoPlayer(QWidget *parent)
    : QWidget(parent)
{
    setWindowTitle(QStringLiteral("双击打开，空格暂停，ESC退出"));
    setWindowIcon(QIcon(":/ico.ico"));
    path=QStandardPaths::writableLocation(QStandardPaths::MoviesLocation);

    m_player = new AVPlayer(this);
    m_vo = new VideoOutput(this);
    if (!m_vo->widget()) {
        QMessageBox::critical(0,QStringLiteral("致命错误"), QStringLiteral("无法创建视频渲染器！"));
        return;
    }
    m_player->setRenderer(m_vo);

    QVBoxLayout *vbox = new QVBoxLayout();
    setLayout(vbox);
    vbox->addWidget(m_vo->widget());

    m_slider = new QSlider();
    m_slider->setOrientation(Qt::Horizontal);
    vbox->addWidget(m_slider);

    connect(m_slider,&QSlider::sliderMoved,this,&VideoPlayer::seek);
    connect(m_player,&AVPlayer::positionChanged,this,&VideoPlayer::updateSlider);
    connect(m_player,&AVPlayer::started,this,&VideoPlayer::updateSlider);
}

VideoPlayer::~VideoPlayer()
{
    if(m_player != nullptr)
        m_player->stop();
}

void VideoPlayer::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
    case Qt::Key_Space:
        detectState();
        break;
    case Qt::Key_Escape:
        if(m_player->isPlaying() || m_player->isPaused())
            stop();
        else
            close();
        break;
    }
}

void VideoPlayer::mouseReleaseEvent(QMouseEvent *)
{
    if(m_player->isPlaying())
        detectState();
}

void VideoPlayer::mouseDoubleClickEvent(QMouseEvent *)
{
    if(!m_player->isPlaying())
        open();
}

void VideoPlayer::open()
{
    QString file = QFileDialog::getOpenFileName(this, QStringLiteral("选择视频文件"),path);
    if (file.isEmpty())
        return;
    m_player->play(file);
}

void VideoPlayer::seek(int pos)
{
    if (!m_player->isPlaying())
        return;
    m_player->seek(pos*1000LL);
}

void VideoPlayer::detectState()
{
    if (!m_player->isPlaying()) {
        m_player->play();
        return;
    }
    m_player->pause(!m_player->isPaused());
}

void VideoPlayer::updateSlider()
{
    m_slider->setRange(0, int(m_player->duration()/1000LL));
    m_slider->setValue(int(m_player->position()/1000LL));
}

void VideoPlayer::stop()
{
    m_player->stop();
}
